package com.qf.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.user.dao.UserDao;
import com.qf.user.entity.User;
import com.qf.user.service.UserService;
import com.qf.utils.JwtUtils;
import com.qf.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.hutool.crypto.digest.DigestUtil;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public ResultVo login(String username, String password) {

        //1. 根据 username查询用户对象
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userDao.selectOne(queryWrapper);

        if (user==null){
            return new ResultVo(-1, "error", "用户名不存在");
        }
        //2. 判断密码是否正确
        String salt = user.getSalt();
        String md5password = DigestUtil.md5Hex(password + salt);

        if (!md5password.equals(user.getPassword())){
            return new ResultVo(-1, "error", "密码错误");
        }

        //3. 生成jwt
        String token = JwtUtils.createToken(username, 120);

        return new ResultVo(1, "ok", token);

    }
}
